package gui;

import java.awt.Dimension;
import java.awt.HeadlessException;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.ProgressMonitor;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableRowSorter;

import org.xml.sax.SAXException;

import util.MainMouseListener;
import ctrl.DBAccess;
import ctrl.EVECentralCtrl;
import data.EVEItem;
import data.EVESystem;
import data.ItemSystemCollection;

public class MainWindow extends JFrame {

  private DBAccess                        _dataBase;
  private ArrayList<ItemSystemCollection> _collections;
  private EVECentralCtrl                  _evecctrl;

  public MainWindow(String title, boolean debug) throws HeadlessException, SAXException, SQLException, IOException {
    super(title);
    setSize(new Dimension(1000, 800));
    // setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    _evecctrl = new EVECentralCtrl();

    // panel.setLayout(new BoxLayout(panel,BoxLayout.X_AXIS));
    // MarketOrderModel marketOrderModel = new MarketOrderModel(item);
    
    TableRowSorter<AbstractTableModel> marketValueSorter = new TableRowSorter<AbstractTableModel>();
    MarketTable marketTable = new MarketTable(marketValueSorter);

//     marketValueSorter.setModel(marketOrderModel);

    _dataBase = new DBAccess();
    _dataBase._initializeDatabase();
    ListContextMenu contextMenu = new ListContextMenu(_evecctrl, _dataBase);

    _collections = new ArrayList<ItemSystemCollection>();
    initialize(debug);


    JScrollPane marketScrollPane = new JScrollPane(marketTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

    JTabbedPane marketTabbedPane = new JTabbedPane();
    marketTabbedPane.addTab("Sell order < Buy order", marketScrollPane);
//    marketTabbedPane.addTab("Buy order < Sell order", new JPanel());

    MainMouseListener mouseListener = new MainMouseListener(marketTable, contextMenu);
    CollectionTabbedPane collectionPane = new CollectionTabbedPane(_collections, marketTable, mouseListener, contextMenu);  

    JSplitPane listAndTableSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, collectionPane, marketTabbedPane);
    add(listAndTableSplitPane);
    listAndTableSplitPane.setResizeWeight(0.3);

    MainMenuBar mainMenu = new MainMenuBar(collectionPane, _evecctrl, _dataBase);
    setJMenuBar(mainMenu);

    setVisible(true);
  }

  private void initialize(boolean debug) throws SQLException, IOException, SAXException {
    _dataBase._connect();
    ResultSet collections = _dataBase._executeQuery("SELECT * FROM users;");
    while (collections.next()) {
      ItemSystemCollection collection = new ItemSystemCollection(collections.getString(1), collections.getString(2));
      _collections.add(collection);
    }
    collections.close();

    Integer dataSize = 0;
    for (ItemSystemCollection collection : _collections) {
      System.out.println("Collection: " + collection.getUserName());

      ResultSet resultSystems = _dataBase._executeQuery("SELECT system_id, eve_system_id, eve_system_name FROM systems, users_systems WHERE systems.system_id = users_systems.system_id AND users_systems.user_id = " + collection.getUserPrimaryKey() + ";");
      while (resultSystems.next()) {
        EVESystem system = new EVESystem(resultSystems.getString(1), resultSystems.getString(2), resultSystems.getString(3));
        collection.addSystem(system);
        System.out.println("Adding system: " + system.getSystemName() + " to collection: " + collection.getUserName());
      }
      resultSystems.close();

      ResultSet resultItems = _dataBase._executeQuery("SELECT item_id, eve_item_id, eve_item_name FROM items, users_items WHERE items.item_id = users_items.item_id AND users_items.user_id = " + collection.getUserPrimaryKey() + ";");
      while (resultItems.next()) {
        EVEItem item = new EVEItem(resultItems.getString(1), resultItems.getString(2), resultItems.getString(3));
        collection.addItem(item);
        dataSize++;
        System.out.println("Adding item: " + item.getItemName() + " to collection: " + collection.getUserName());
      }
      resultItems.close();
    }
    _dataBase._disconnect();

    
    Integer progress = 0;
    ProgressMonitor progressMonitor = null;
    if (!debug) {
      progressMonitor = new ProgressMonitor(null, "Loading data from EVE-Central", "Completed 0 %.\n", 0, dataSize);
    }

    for (ItemSystemCollection collection : _collections) {
      for (EVEItem item : collection.getItems()) {
        for (EVESystem system : collection.getSystems()) {
          item._addSystem(system);
        }
        if (!debug) {
          _evecctrl._retrieveMarketData(item);
          progress++;
          _increaseProgress(progressMonitor, progress.floatValue(), dataSize.floatValue());
        }
      }
    }
  }

  public void _increaseProgress(ProgressMonitor progressMonitor, float currentProgress, float maxProgress) {
    progressMonitor.setProgress((int) currentProgress);
    float percent = (currentProgress / maxProgress) * 100.0f;
    String note = String.format("Completed %d%%.\n", (int) percent);
    progressMonitor.setNote(note);
    if (progressMonitor.isCanceled()) {
      System.exit(-1);
    }
  }
}
